package com.hongxun.design.activitys;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.acceptance.mode.ProblemR;
import com.hongxun.design.acceptance.mode.ServerData;
import com.hongxun.design.acceptance.mode.problem;
import com.hongxun.design.acceptance.mode.problemPhoto;
import com.hongxun.design.constant.Constant;
import com.hongxun.design.interfaces.BottomPanelCallback;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.mytools.ShardPreferencesTool;
import com.hongxun.design.service.CacheService;
import com.hongxun.design.ui.headandbottonpanel.BottomControlPanel;
import com.hongxun.design.ui.headandbottonpanel.HeadControlPanel;
import com.hongxun.design.utils.FragmentUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.httputil.HttpStringUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zerdoor_pc on 2016/4/26.
 * 主Activity（主要负责下方按钮的Fragment切换）
 */
public class HomePageActivity extends BaseActivity implements BottomPanelCallback {
    BottomControlPanel bottomPanel = null;
    public HeadControlPanel headPanel = null;
    FragmentUtil fragmentUtil = null;
    Handler scheduleCountHandler, newHandler;
    Handler textHandler;
    private ServiceConnection sc;
    CacheService.SimpleBinder sBinder;

    @Override
    public void Nofity() {
        scheduleCountHandler.sendEmptyMessage(1);
        super.Nofity();

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (MyApp.ISOUTLOGIN) {
            MyApp.ISOUTLOGIN = false;
            MyApp.currProject.setBean(MyApp.File.LoadFileData_ProjectItem(MString.currProject), 0);//获取上次浏览项目
            MyApp.HomeActivity = this;
            addScheduleCountHandler();
            initUI();
            fragmentUtil = FragmentUtil.getIntence(this);
            fragmentUtil.setDefaultFirstFragment(Constant.FRAGMENT_FLAG_HOME, bottomPanel);
            openService();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_homepage);
        if (MyApp.currProject != null)
            MyApp.currProject.setBean(MyApp.File.LoadFileData_ProjectItem(MString.currProject), 0);//获取上次浏览项目
        MyApp.HomeActivity = this;
        addScheduleCountHandler();
        initHandler();
        initUI();
        fragmentUtil = FragmentUtil.getIntence(this);
        fragmentUtil.setDefaultFirstFragment(Constant.FRAGMENT_FLAG_HOME, bottomPanel);
        openService();
        getAccpetRec();//加载一次
    }

    //基础项目数据存储(每次有网登陆更新基本数据)
    private void initHandler() {
        newHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED://存储当前角色涉及到的基础数据
                        String valueOf = String.valueOf(msg.obj).replaceAll("\\\\n", "");
                        ServerData libPro = JSON.parseObject(valueOf, ServerData.class);
                        Context context = getApplicationContext();
                        List<problem> problems = libPro.getProblemList();
                        List<ProblemR> problemRs = libPro.getProblemTermList();
                        List<problemPhoto> problemPhotos = libPro.getProblemPhotoList();
                        if (problems == null) problems = new ArrayList<>();
                        if (problemRs == null) problemRs = new ArrayList<>();
                        if (problemPhotos == null) problemPhotos = new ArrayList<>();
                        //设置点位对应的大类
//                        for (ProblemR problemR : problemRs) {
//
//                        }
                        ShardPreferencesTool.save(context, MString.library, FastJsonUtil.beanToJson(problems),1);
                        ShardPreferencesTool.save(context, MString.lib_point, FastJsonUtil.beanToJson(problemRs),1);
                        ShardPreferencesTool.save(context, MString.libraryPhoto, FastJsonUtil.beanToJson(problemPhotos),1);
                        break;
                }
            }
        };
    }


    /**
     * 开启服务*
     */
    private void openService() {
        if (sc == null) sc = new ServiceConnection() {

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }

            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                sBinder = (CacheService.SimpleBinder) service;
            }
        };
        bindService(new Intent(this, CacheService.class), sc, Context.BIND_AUTO_CREATE);
    }

    /**
     * 关闭服务*
     */
    public void closeService() {
        if (sc != null) unbindService(sc);
        sc = null;
    }


    /**
     * 通用数据请求*
     */
    public void getScheduleCount(Handler textHandler) {
        this.textHandler = textHandler;
        MyApp.HTTP.http.isLoad = false;
        MyApp.HTTP.getScheduleCount(scheduleCountHandler, HttpStringUtil.SUCCESSED);
    }

    public void getAccpetRec() {
        if (MyApp.NetWorkConnect) MyApp.HTTP.getAcceptRecord(newHandler, HttpStringUtil.SUCCESSED);
    }

    private void addScheduleCountHandler() {
        scheduleCountHandler = new Handler() {
            boolean flag = true;

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            MyApp.scheduleCountBean = FastJsonUtil.JsonToGetScheduleCountBean((String) msg.obj);
                            if (flag) {
                                flag = false;
                                fragmentUtil.homeFragment.Refresh();
                            }
                            if (textHandler != null) {
                                textHandler.sendEmptyMessage(1);
                                textHandler = null;
                            }
                        }
                        MyApp.HTTP.getSysImgTypeList(scheduleCountHandler, 11);
                        break;
                    case HttpStringUtil.ERROR:
                        break;
                    case 1:
                        bottomPanel.setupdate();
                        fragmentUtil.myFragment.Refresh();
                        break;
                    case 11:
                        MyApp.getInstance().saveImgTypeList(String.valueOf(msg.obj));
                        break;
                }
            }
        };
    }

    private void initUI() {
        bottomPanel = (BottomControlPanel) findViewById(R.id.bottom_layout);
        if (bottomPanel != null) {
            bottomPanel.initBottomPanel();
            bottomPanel.setBottomCallback(this);
        }
        headPanel = (HeadControlPanel) findViewById(R.id.head_layout);
        if (headPanel != null) {
            headPanel.initHeadPanel();
        }
    }

    @Override
    protected void onStart() {
        MyApp.activity = this;

        super.onStart();
    }

    @Override
    protected void onResume() {
        if (tag.length() != 0) {
            bottomPanel.setCheck(tag);
            tag = "";
        }
        MyLog.L(MString.SUCCESSED + "刷新1");
        getScheduleCount(null);
        MyApp.ChangeToOldProject();
        super.onResume();
    }

    private String tag = "";

    public void clickButton(String tag) {

        MyLog.L(MString.SUCCESSED + "切换tag：" + tag);
        this.tag = tag;

    }

    /* 处理BottomControlPanel的回调
     ** BottomControlPanel.BottomPanelCallback#onBottomPanelClick(int)
	 * 监听下方按钮点击
	 */
    @Override
    public void onBottomPanelClick(int itemId) {
        String tag = "";
        if ((itemId & Constant.BTN_FLAG_MESSAGE) != 0) {
            tag = Constant.FRAGMENT_FLAG_HOME;
        } else if ((itemId & Constant.BTN_FLAG_CONTACTS) != 0) {
            tag = Constant.FRAGMENT_FLAG_PROJECT;
        } else if ((itemId & Constant.BTN_FLAG_NEWS) != 0) {
            tag = Constant.FRAGMENT_FLAG_ENCYCLOPEDIAS;
        } else if ((itemId & Constant.BTN_FLAG_SETTING) != 0) {
            tag = Constant.FRAGMENT_FLAG_MY;

        }
        MyLog.L(MyApp.AppName + "tag =" + tag);
        if (fragmentUtil.currtag.equals(tag)) return;
        fragmentUtil.setTabSelection(tag); //切换Fragment
        headPanel.setMiddleTitle(tag);//切换标题
    }


    @Override
    protected void onStop() {
        super.onStop();
        FragmentUtil.currFragTag = "";
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
    }

    @Override
    public void onBackPressed() {
        back();
    }

    private long mExitTime;

    private void back() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Object mHelperUtils;
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        closeService();
        fragmentUtil.destory();
        System.exit(0);
        super.onDestroy();
    }


}
